﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Goods.Entity;
using NewRetail.Application.Components.Warehouse.Entity;
using NewRetail.Application.Core;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("fullcut-category")]
    public class PromoteSaleFullCutCategoryController : BaseController<PromoteSalesFullCutCategory>
    {
        public override async Task<ResponseEntity<PagedResultDto<PromoteSalesFullCutCategory>>> QueryPaging([FromBody] PagingRequestDto dto)
        {
            var res = await base.QueryPaging(dto);

            if (res.Data?.Items?.Any() ?? false)
            {
                var db = await this.Repo.GetDbContextAsync();
                await db.AttachData<GoodsCategory, PromoteSalesFullCutCategory>(res.Data.Items,
                    x => x.categoryID,
                    (m, arr) => m.GoodsCategory = arr.FirstOrDefault());
                await db.AttachData<PromoteSalesFullCut, PromoteSalesFullCutCategory>(res.Data.Items,
                    x => x.fullCutID,
                    (m, arr) => m.PromoteSalesFullCut = arr.FirstOrDefault());
            }

            return res;
        }

        [HttpPost("add-multiple")]
        public async Task<ResponseEntity<PromoteSalesFullCutCategory[]>> AddMultiple([FromBody] PromoteSalesFullCutCategory[] data)
        {
            data.Should().NotBeNullOrEmpty();
            foreach (var m in data)
            {
                this.EntityHelper.InitEntity(m);
            }

            var ids = data.Select(x => x.categoryID).Distinct().ToArray();

            await this.Repo.DeleteAsync(x => ids.Contains(x.categoryID), autoSave: true);
            await this.Repo.InsertManyAsync(data, autoSave: true);

            return new ResponseEntity<PromoteSalesFullCutCategory[]>().SetData(data);
        }
    }
}
